package com.wisdom.server.handler;

import com.wisdom.core.data.RpcRequest;
import com.wisdom.core.data.RpcResponse;
import com.wisdom.core.factory.SpringBeanFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @description: <根据RpcRequest的信息匹配服务进行业务逻辑处理>
 * @author: Leo
 * @date:2021-08-22 15:37
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcRequestHandler extends SimpleChannelInboundHandler<RpcRequest> {


    /*
            Sharable  做共享处理  将需要的成员信息共享出去
     */

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest rpcRequest) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("rpc server received request, request msg is {}", rpcRequest);
        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setRequestId(rpcRequest.getRequestId());

        //根据 rpcRequest 的信息  进行业务逻辑处理 此处使用反射调用的方式处理
        String className = rpcRequest.getClassName();
        Object[] parameters = rpcRequest.getParameters();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        String methodName = rpcRequest.getMethodName();
        Object bean = SpringBeanFactory.getBean(Class.forName(className));
        Method method = bean.getClass().getMethod(methodName, parameterTypes);
        Object result = method.invoke(bean, parameters);
        rpcResponse.setResult(result);
        ctx.channel().writeAndFlush(rpcResponse);
    }

}
